package com.vertx.starter.guice;

import com.google.inject.Injector;
import io.vertx.core.Promise;
import io.vertx.core.Verticle;
import io.vertx.core.impl.verticle.CompilingClassLoader;
import io.vertx.core.spi.VerticleFactory;

import java.util.concurrent.Callable;

public class GuiceVerticalFactory implements VerticleFactory {

    private final Injector injector;

    public GuiceVerticalFactory(Injector injector) {
        this.injector = injector;
    }

    @Override
    public String prefix() {
        return "guice";
    }

    @Override
    public void createVerticle(String verticleName, ClassLoader classLoader, Promise<Callable<Verticle>> promise) {
        verticleName = VerticleFactory.removePrefix(verticleName);

        Class clazz;
        try {
            if (verticleName.endsWith(".java")) {
                CompilingClassLoader compilingLoader = new CompilingClassLoader(classLoader, verticleName);
                String className = compilingLoader.resolveMainClassName();
                clazz = compilingLoader.loadClass(className);
            } else {
                clazz = classLoader.loadClass(verticleName);
            }
        } catch (ClassNotFoundException var7) {
            promise.fail(var7);
            return;
        }

        promise.complete(() -> {
            return (Verticle) this.injector.getInstance(clazz);
        });
    }
}
